package cn.sibu.disalllowtouchintercept;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class DownloadActivity extends AppCompatActivity {

    private static final  String DL_ID = "download";
    private SharedPreferences prefs;

    private DownloadManager dm;
    private ImageView imageView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imageView = new ImageView(this);
        setContentView(imageView);

        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!prefs.contains(DL_ID)){
            //开始下载
            Uri resource = Uri.parse("http://pics.sc.chinaz.com/files/pic/pic9/201512/apic16820.jpg");
            DownloadManager.Request request =
                    new DownloadManager.Request(resource);
            //设置允许的连接来处理下载
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
            request.setAllowedOverRoaming(false);
            //request.setDestinationInExternalPublicDir();
            //在通知栏上显示
            request.setTitle("Download Sample");

            long id = dm.enqueue(request);
            //保存唯一的id
            prefs.edit().putLong(DL_ID,id).commit();
        }else {
            //下载已经开始,检查下载状态
            queryDownloadStatus();
        }
        registerReceiver(receiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("onReceive","onReceive");
            queryDownloadStatus();
        }
    };

    private void queryDownloadStatus(){
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(prefs.getLong(DL_ID,0));
        Cursor c= dm.query(query);

        if(c.moveToFirst()){
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status){
                case DownloadManager.STATUS_PAUSED:
                case DownloadManager.STATUS_PENDING:
                case DownloadManager.STATUS_RUNNING:
                    //什么也不做下载依然进行
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    //下载完成,显示图片

                    try {
                        ParcelFileDescriptor file = dm.openDownloadedFile(prefs.getLong(DL_ID,0));
                        FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(file);
                        imageView.setImageBitmap(BitmapFactory.decodeStream(fis));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                case DownloadManager.STATUS_FAILED:
                    //清除下载并稍后重试
                    dm.remove(prefs.getLong(DL_ID, 0));
                    prefs.edit().clear().commit();
                    break;
            }
        }
    }
}

